/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.garagesale.admin.action;

import com.garagesale.config.hibernate.HibernateUtil;
import com.garagesale.data.DBAccess;
import com.garagesale.data.ItemCategory;
import com.garagesale.data.Item;
import com.garagesale.data.User;
import com.garagesale.data.Administrator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import java.io.PrintWriter;
import java.util.Iterator;
import org.hibernate.Session;

/**
 *
 * @author christophe
 */
public class DeleteUserAction extends org.apache.struts.action.Action {
    
    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    
    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //PrintWriter pw = new PrintWriter("/Users/stolworthyfamily/Documents/testFile");
        //pw.println("1");
        //pw.flush();
        DBAccess dbAccess = DBAccess.getInstance();
        String userIdString = request.getParameter("userID");
        if(userIdString != null && ! userIdString.isEmpty()) {
            try {
                Integer userId = Integer.parseInt(userIdString);

                Session session = HibernateUtil.getSessionFactory().openSession();
                User foundUser = (User)session.get(User.class, userId);
                session.close();

                if(foundUser != null) {
                    dbAccess.delete(foundUser);
                }
            } catch(NumberFormatException nfe) {
                
            }
        }
        
        List<User> result = dbAccess.retrieveAllUsers();
        request.setAttribute("users", result);
            

        return mapping.findForward("welcome");
    }
}